<template>
  <el-card>
    <el-input class="width200" placeholder="名称" v-model="name" clearable></el-input>
    <el-button type="primary" @click="searchList()">搜索模版</el-button>
    <el-button type="primary" @click="showGood">新增模版</el-button>
    <el-table :data="tableData" stripe border style="margin-top: 20px">
      <el-table-column prop="_id" label="id">
      </el-table-column>
      <el-table-column prop="name" label="名称">
      </el-table-column>
      <el-table-column prop="des" label="备注">
      </el-table-column>
      <el-table-column  label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[100, 200, 300, 400]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    <el-dialog :visible.sync="isCoupon" :close-on-click-modal="true" width="60%">
      <el-form ref="form" :model="obj" label-width="80px">
        <el-form-item label="名称">
          <el-input class="width400" v-model="obj.name"></el-input>
        </el-form-item>
        <el-form-item label="签约图片">
          <vk-data-upload v-model="obj.imageList" :limit="9"></vk-data-upload>
        </el-form-item>
        <el-form-item label="签字位置">
          <el-input class="width400" v-model="obj.locationList"></el-input>
        </el-form-item>
        <el-form-item label="上传协议">
          <!-- 不需要引入，可直接使用 -->
          <lRichTextEditor
          	:value="obj.url"
          	@change="GetChange"
          	>
          </lRichTextEditor>
        </el-form-item>
        <el-form-item label="备注">
          <el-input class="width400" v-model="obj.des"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">更新</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</template>

<script>
  export default {
    data() {
      return {
        name: '',
        obj: {
          name: '',
        url: '测试',
          des: ''
        },

        currentPage: 1,
        pageNum: 1,
        pageSize: 100,
        total: 0,
        isCoupon: false,
        tableData: [],
      }
    },
    mounted() {
      this.getList()
    },
    methods: {
      GetChange(e){
        // this.obj.url = e.substr(15)
      	// console.log(e.substr(15))
        // console.log(this.obj.url)
      },
      showGood() {
        this.isCoupon = true
        this.obj= {
          name: '',
          url: '',
          des: ''
        }
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.pageNum = val
        this.getList()
      },
      handleEdit(index, row) {
        this.isCoupon = true
        this.obj = JSON.parse(JSON.stringify(row))
      },
      handleDelete(index, row) {
        vk.confirm('确定要删除该模版吗', '提示', '确定', '取消', res => {
          if (res.confirm) {
            this.goodDelete(row)
          }
        });
      },
      goodDelete(row) {
        uni.showLoading({
          title: '加载中...'
        })
        let that = this
        vk.callFunction({
          url: 'user/kh/templateDelete',
          data: {
            _id: row._id
          },
          success: (res) => {
            if (res) {
              uni.hideLoading()
              this.getList()
            }
          }
        })
        // 先查询一下是否有关联券包
        // vk.callFunction({
        //   url: 'user/pub/couponAllget',
        //   data: {
        //     relate_template_id: row._id
        //   },
        //   success: (res) => {
        //     if (res && res.rows.length == 0) {
        //       vk.callFunction({
        //         url: 'user/kh/templateDelete',
        //         data: {
        //           _id: row._id
        //         },
        //         success: (res) => {
        //           if (res) {
        //             uni.hideLoading()
        //             this.getList()
        //           }
        //         }
        //       })
        //     } else {
        //       vk.toast('该模版关联了券包，请先删除对应券包','none');
        //     }
        //   }
        // })
      },
      uploadFile(){
      			// let type = that.queryForm1.formData.type;
      			let extension = [];
      			// if(type === "image"){
      			// 	extension = ["png", "jpg", "jpeg", "gif", "bmp", "svg", "webp", "jfif", "dpg"];
      			// 	fileType = "image";
      			// }else if(type === "video"){
      			// 	extension = ["avi", "mp3", "mp4", "3gp", "mov", "rmvb", "rm", "flv", "mkv", "wmv", "m3u8", "mpg", "mpeg", "dat", "asf"];
      			// 	fileType = "video";
      			// }else if(type === "other"){
      			// 	extension = ["txt","pdf","xls","xlsx","ppt","pptx","doc","docx","rar","zip"];
      			// }
            extension = ["pdf","doc","docx"]
            let that = this
      			uni.chooseFile({
      				extension,
      				success: async res => {
      					let item = {
      						tempFilePaths: res.tempFilePaths,
      						tempFiles: res.tempFiles,
      					};
                console.log(res, 'rex-=-==')
      					// vk.pubfn.openForm('uploadProgress', { item });
      					vk.showLoading("上传中...");
      					for (let i = 0; i < res.tempFilePaths.length; i++) {
      						let percentage = vk.pubfn.toDecimal((i+1) / res.tempFilePaths.length * 100, 0);
      						try {
      							let info = await vk.uploadFile({
      								filePath: res.tempFilePaths[i],
      								file: res.tempFiles[i],
      								needSave: true,
      								onUploadProgress:function(progressRes){
      									// 上传过程中
      									vk.showLoading(`文件${i+1}：${progressRes.progress}%\n`);
      								},
      							});
                    console.log(info, 'info----')
                    this.template.url = info.url
      							vk.showLoading(`总上传进度：${percentage}%`);
      						} catch(err){
      							console.error(err);
      						}
      					}
      					vk.hideLoading();
      				}
      			});
      		},
      searchList() {
        this.pageNum = 1
        this.getList()
      },
      getList() {
        uni.showLoading({
          title: '加载中...'
        })
        let that = this
        let obj = {}
        if (this.name) {
          obj.name = this.name
        }
        vk.callFunction({
          url: 'user/kh/templateList',
          data: {
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            ...obj
          },
          success: (res) => {
            if (res) {
              uni.hideLoading()
              this.tableData = res.rows
              this.total = res.total
            }
          }
        })
      },
      onSubmit() {
        uni.showLoading({
          title: '加载中...'
        })
        let that = this
        vk.callFunction({
          url: 'user/kh/templatePost',
          data: that.obj,
          success: (res) => {
            if (res) {
              uni.hideLoading()
              console.log(res)
              that.isCoupon = false
              that.getList()
            }
          }
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
  /deep/.el-tabs__new-tab {
    margin-right: 12px !important
  }
.update-img {
  width: 100px;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-direction: column;
	color: #d5d5de;
  border: 1px solid #ccc;
	&::before {
		line-height: 1;
		font-size: 45px;
		content: "+";
	}
	&::after {
		content: "上传";
		font-size: 12px;
	}
}
.update-txt {
  width: 300px;
  display: inline-block;
  white-space: nowrap;
  	overflow: hidden;
  	text-overflow: ellipsis;
}
  .width400 {
    width: 400px
  }

  .width200 {
    width: 200px
  }
  .width100 {
    width: 100px
  }
  .good {
    display: flex;
    align-items: center;
    margin-top: 10px;
    &-img {
      width: 30px;
      height: 30px;
      border-radius: 4px;
    }
    &-name {
      margin-left: 10px;
    }
    &-price {
      color: #f56c6c;
      font-weight: 500;
      margin-left: 10px;
      margin-right: 10px;
    }
  }
</style>